<?php

namespace App\Http\Controllers\Agent;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class SupplierController extends Controller
{
    public $agent;

    public function __construct()
    {
        $this->middleware(['agent']);
        $this->agent = Auth::guard('agent')->user();
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = Supplier::where('status', '>', '-1')->where('agent_id', $this->agent->id);
        !empty($params['name']) && $model->where('name', 'like', "%{$params['name']}%");
        !empty($params['phone']) && $model->where('phone', $params['phone']);
        isset($params['status']) && $params['status'] !== '' && $model->where('status', $params['status']);
        $list = $model->orderBy('id', 'desc')->paginate(15);
        return view('agent.supplier.index', [
            'list' => $list,
            'params' => $params,
        ]);
    }

    public function add(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'name' => 'required|unique:supplier',
                    'phone' => 'required',
                ], [
                    'name.required' => '名字必填',
                    'name.unique' => '该名字已存在',
                    'phone.required' => '手机号必填',
                ]);

                $params = $request->all();
                if (!preg_match('/^1\d{10}$/', $params['phone']))
                    throw new BizException('手机号格式不正确');

                $params['agent_id'] = $this->agent->id;
                $params['created_at'] = date('Y-m-d H:i:s');
                $params['updated_at'] = date('Y-m-d H:i:s');
                Supplier::insert($params);
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            return view('agent.supplier.add');
        }
    }

    public function edit(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'name' => 'required',
                    'phone' => 'required',
                ], [
                    'name.required' => '名字必填',
                    'phone.required' => '手机号必填',
                ]);

                $params = $request->all();
                $id = $params['id'];

                $supplier = Supplier::where('id', '!=', $id)->where('name', $params['name'])->first();
                if (!empty($supplier))
                    throw new BizException('该名字已存在');

                if (!preg_match('/^1\d{10}$/', $params['phone']))
                    throw new BizException('手机号格式不正确');

                if (isset($params['id']))
                    unset($params['id']);
                Supplier::where('id', $id)->update($params);
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            $row = Supplier::find($request->input('id'));
            if ($row['agent_id'] != $this->agent->id)
                return '你无权修改';

            return view('agent.supplier.edit', ['row' => $row]);
        }
    }

    public function del(Request $request)
    {
        Supplier::where('id', $request->input('id'))->update(['status' => -1]);
        return response()->json(['status' => 1, 'info' => '删除成功']);
    }
}